<template>
	<view class="checkout-container">
		<!-- 收货地址 -->
		<view class="address-section">
			<view v-if="selectedAddress" class="address-info">
				<view class="address-top" @click="selectAddress">
					<text class="name">{{selectedAddress.name}}</text>
					<text class="phone">{{selectedAddress.mobile}}</text>
				</view>
				<view class="address-detail" @click="selectAddress">
					{{selectedAddress.province}}{{selectedAddress.city}}{{selectedAddress.area}}{{selectedAddress.address}}
				</view>
				<view class="addressEdit" @click="toggle('center')">
					修改收货地址
				</view>
			</view>
			<image v-if="selectedAddress" @click="selectAddress" class="arrow" src="/static/images/jt.png"></image>
			<view v-else class="no-address" @click="toggle('center')">
				<text>请添加收货地址</text>
			</view>
		</view>

		<!-- 商品清单 -->
		<view class="goods-section">
			<view class="section-title">商品清单</view>
			<view class="goods-list">
				<view class="goods-item" v-for="(item, index) in selectedGoods" :key="index">
					<image class="goods-image" :src="item.thumb" mode="aspectFill"></image>
					<view class="goods-info">
						<view class="goods-name">{{item.title}}</view>
						<view class="box">
							<view class="goods-spec">库存量:{{item.num}}/{{item.specs}}</view>
							<view class="item-count">
								<text class="count-btn" @click="changeCount(index, -1)">-</text>
								<text class="count-num">{{item.count}}</text>
								<text class="count-btn" @click="changeCount(index, 1)">+</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!--  -->


		<!-- 价格明细 -->
		<!-- 	<view class="price-section">
			<view class="price-row">
				<text>商品总价</text>
				<text>¥{{totalPrice}}</text>
			</view>
			<view class="price-row">
				<text>运费</text>
				<text>¥{{shippingFee>0?shippingFee:'全国包邮'}}</text>
			</view>
			<view class="price-row" v-if="selectedCoupon">
				<text>礼品卡</text>
				<text class="discount">-¥{{selectedCoupon.value}}</text>
			</view>
			<view class="price-row total">
				<text>实付款</text>
				<text class="total-price">¥{{actualPayment}}</text>
			</view>
		</view> -->
		<!-- 地区选择器 -->

		<!-- 底部提交栏 -->
		<view class="footer" style="justify-content: center;">
			<!-- <view class="price-info">
				<text>合计: </text>
				<text class="price">¥{{actualPayment}}</text>
			</view> -->
			<view class="submit-btn" @click="submitOrder">立即配送</view>
		</view>
		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
				<adAddress ref="adAddress" @confirm="onAddressConfirm" />
			</view>
		</uni-popup>
	</view>
</template>
<script>
	import {
		request
	} from '@/utils/request.js'
	import adAddress from '@/components/ad-address/ad-address.vue'
	export default {
		components: {
			adAddress
		},
		data() {
			return {
				addressList: [],
				type: 0,
				selectedGoods: [], // 从购物车选择的商品
				selectedAddress: null, // 选择的地址
				selectedCoupon: null, // 选择的优惠券
				remark: '', // 订单备注
				shippingFee: 0, // 运费
				coupons: [ // 可用优惠券列表
					{
						id: 1,
						name: '新用户优惠券',
						value: 20,
						condition: '满100元可用'
					},
					{
						id: 2,
						name: '节日优惠券',
						value: 10,
						condition: '无门槛'
					}
				]
			}
		},
		computed: {
			// 商品总价
			totalPrice() {
				return this.selectedGoods.reduce((total, item) => {
					return total + (item.price * item.count)
				}, 0).toFixed(2)
			},
			// 实际支付金额
			actualPayment() {
				let payment = parseFloat(this.totalPrice) + parseFloat(this.shippingFee)
				if (this.selectedCoupon) {
					payment -= parseFloat(this.selectedCoupon.value)
				}
				return payment > 0 ? payment.toFixed(2) : '0.00'
			}
		},
		onLoad(options) {
			console.log(options)
			if (options.type) {
				this.type = options.type
			}
			// 从购物车页面传递过来的选中商品
			if (options.items) {
				this.selectedGoods = JSON.parse(decodeURIComponent(options.items))
				this.selectedGoods = this.selectedGoods.map(item => ({
					...item,
					count: parseInt(item.count || 1)
				}))
			}
			// 获取默认地址
			this.getDefaultAddress();
			// this.getAddressList()

		},
		methods: {
			getAddressList() {

			},
			toggle(type) {
				this.type = type
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.open(type)
			},
			// 修改地址
			chengeAddress() {
				console.log(this.selectedAddress)
				this.$refs.adAddress.updateAddress(this.selectedAddress)
			},
			onAddressConfirm(confim) {
				console.log(confim)
				this.selectedAddress = confim;
				this.$refs.popup.close()
			},
			// 获取默认地址
			getDefaultAddress() {
				// 这里应该是API请求，模拟数据
				request({
					url: 'address/list',
					method: 'get',
					data: {}
				}).then(res => {
					if (res.status == 200) {
						this.addressList = res.data;
						const result = this.addressList.find(item => item.is_default == 1) ?? addressList[0];
						this.selectedAddress = result
						console.log(result)
						this.chengeAddress()
					}
				})
			},

			// 选择地址
			selectAddress() {
				uni.navigateTo({
					url: '/pages/addressList/addressList?selectMode=true'
				})
			},

			// 选择优惠券
			selectCoupon() {
				uni.showToast({
					title: '暂无礼品卡',
					icon: 'none',
					duration: 2000
				});
				// uni.navigateTo({
				// 	url: '/pages/coupon/list?total=' + this.totalPrice
				// })
			},

			// 提交订单
			submitOrder() {
				if (!this.selectedAddress) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					})
					return
				}

				uni.showLoading({
					title: '提交中...'
				})
				let params = {
					godown: '',
					address_id: this.selectedAddress.id
				}

				let shouldStop = false; // 标志位

				for (let i = 0; i < this.selectedGoods.length; i++) {
					const item = this.selectedGoods[i];
					if (item.gid == 1) {
						if (item.count % 2 != 0) {
							shouldStop = true;
							break;
							
						}
					}
					if (item.gid == 2) {
						if (item.count % 12 != 0) {
							shouldStop = true;
							break;
						}
					}

				}

				// 只有没触发过break时才执行
				if (shouldStop) {
					uni.showToast({
						title:'必须整件才能配送哦',
						icon:'none'
					})
					console.log(333);
					return
				}
				console.log(444)
				params.godown = JSON.stringify(this.selectedGoods.map(({
					id,
					count
				}) => ({
					id,
					num: count
				})));
				// 模拟API请求
				request({
					url: 'user/godown-send',
					method: 'post',
					data: params
				}).then(res => {
					if (res.status == 200) {
						uni.hideLoading()
						// this.cartList = res.data.list
						// this.cartList = res.data
						this.toMSg()
						uni.redirectTo({
							url: '/pages/orderList/orderList'
						})
					}
				})

				// 跳转到支付页面

			},
			toMSg(){
				uni.requestSubscribeMessage({
				  tmplIds: ['sMnAXXnoF7XjBT4AlPwrnhwKjgoOqirfhBsUkJPN9Ng', 'a-22GtkmzTO9QOY85NlXKN4WB8J6HE4qgge-SRRwfCo'],
				  success (res) {
				    console.log('订阅消息授权结果：', res);
				    // 可以在这里处理授权结果，例如：
				    // if (res['sMnAXXnoF7XjBT4AlPwrnhwKjgoOqirfhBsUkJPN9Ng'] === 'accept') {
				    //   console.log('第一个模板消息授权成功');
				    // }
				  },
				  fail (err) {
				    console.error('订阅消息调用失败：', err);
				  },
				  complete () {
				    // 无论成功失败都会执行
				  }
				});
			},
			// 修改商品数量
			changeCount(index, num) {
				const newCount = this.selectedGoods[index].count * 1 + num * 1;
				console.log(newCount)
				if (newCount > this.selectedGoods[index].num) {
					uni.showToast({
						title: '商品数量不能超过当前库存数量',
						icon: 'none'
					})
					return
				}
				if (newCount < 1) {
					uni.showToast({
						title: '商品数量不能少于1',
						icon: 'none'
					})
					return
				}
				if (newCount > 99) {
					uni.showToast({
						title: '商品数量不能超过99',
						icon: 'none'
					})
					return
				}
				this.selectedGoods[index].count = newCount
				this.$forceUpdate()
			},
		}
	}
</script>
<style lang="scss">
	.checkout-container {
		padding-bottom: 100rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 地址部分 */
	.address-section {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		position: relative;
		display: flex;
		align-items: center;
	}

	.address-info {
		flex: 1;
		position: relative;

		.addressEdit {
			right: 0;
			bottom: 0;
			color: red;
			font-size: 26rpx;
			margin-top: 30rpx;
		}
	}

	.address-top {
		margin-bottom: 15rpx;
	}

	.address-top .name {
		font-size: 32rpx;
		font-weight: bold;
		margin-right: 20rpx;
	}

	.address-top .phone {
		font-size: 28rpx;
		color: #666;
	}

	.address-detail {
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
	}

	.no-address {
		flex: 1;
		font-size: 28rpx;
		color: #999;
	}

	.arrow {
		width: 40rpx;
		height: 40rpx;
		margin-left: 20rpx;
	}

	/* 各部分通用样式 */
	.section-title {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #eee;
	}

	/* 商品列表 */
	.goods-section {
		background-color: #fff;
		margin-bottom: 20rpx;
	}

	.goods-list {
		padding: 20rpx 30rpx;

		.box {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
	}

	.goods-item {
		display: flex;
		margin-bottom: 30rpx;
	}

	.goods-item:last-child {
		margin-bottom: 0;
	}

	.goods-image {
		width: 150rpx;
		height: 150rpx;
		border-radius: 8rpx;
	}

	.goods-info {
		flex: 1;
		margin-left: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.goods-name {
		font-size: 28rpx;
		color: #333;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.goods-spec {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.goods-price-row {
		display: flex;
		justify-content: space-between;
		margin-top: 10rpx;
	}

	.goods-price {
		font-size: 28rpx;
		color: #e74c3c;
		font-weight: bold;
	}

	.goods-count {
		font-size: 26rpx;
		color: #999;
	}

	/* 优惠券部分 */
	.coupon-section {
		background-color: #fff;
		margin-bottom: 20rpx;
	}

	.coupon-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 30rpx;
	}

	.coupon-right {
		display: flex;
		align-items: center;
	}

	.coupon-value {
		color: #e74c3c;
		margin-right: 15rpx;
	}

	/* 备注部分 */
	.remark-section {
		background-color: #fff;
		margin-bottom: 20rpx;
	}

	.remark-input {
		height: 120rpx;
		padding: 20rpx 30rpx;
		font-size: 28rpx;
		width: 100%;
		box-sizing: border-box;
	}

	/* 价格明细 */
	.price-section {
		background-color: #fff;
		padding: 0 30rpx;
	}

	.price-row {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0;
		font-size: 28rpx;
		color: #666;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.price-row:last-child {
		border-bottom: none;
	}

	.discount {
		color: #e74c3c;
	}

	.price-row.total {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
	}

	.total-price {
		color: #e74c3c;
		font-size: 36rpx;
	}

	/* 底部提交栏 */
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.price-info {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.price {
		color: #e74c3c;
		font-size: 32rpx;
		font-weight: bold;
	}

	.submit-btn {
		width: 220rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #e74c3c;
		color: #fff;
		border-radius: 40rpx;
		font-size: 30rpx;
	}

	.item-count {
		display: flex;
		align-items: center;
	}

	.count-btn {
		width: 50rpx;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		border: 1rpx solid #ddd;
		font-size: 32rpx;
	}

	.count-num {
		width: 70rpx;
		text-align: center;
		font-size: 28rpx;
	}
</style>